package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @PostMapping("/submit")
    @Transactional
    public R submit(@RequestBody Orders orders){
        orderService.submitOrders(orders);
        return R.success(null);
//        Long user_Id = BaseContext.getCurrentId();
//        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,user_Id);
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
//        if (shoppingCarts==null || shoppingCarts.size()==0){
//            throw new CustomException("购物车为空,下单失败");
//        }
//        //订单表里需要用户信息和地址信息
//        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        userLambdaQueryWrapper.eq(User::getId,user_Id);
//        User user = userService.getOne(userLambdaQueryWrapper);
//
//        Long addressBookId = orders.getAddressBookId();
//        AddressBook addressBook = addressBookService.getById(addressBookId);
//        if (addressBook==null){
//            throw new CustomException("地址未填写,请先填写地址再下单");
//        }
//        long orderId = IdWorker.getId();//订单号
//        AtomicInteger amount = new AtomicInteger(0);
//        orders.setId(orderId);
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setCheckoutTime(LocalDateTime.now());
//        orders.setStatus(2);
//        orders.setAmount(new BigDecimal(amount.get()));//总金额
//        orders.setUserId(user_Id);
//        orders.setNumber(String.valueOf(orderId));
//        orders.setUserName(user.getName());
//        orders.setConsignee(addressBook.getConsignee());
//        orders.setPhone(addressBook.getPhone());
//        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
//                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
//                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
//                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
//        //向订单表插入数据，一条数据
//        orderService.save(orders);
//        //组装订单明细信息
//        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
//            OrderDetail orderDetail = new OrderDetail();
//            orderDetail.setOrderId(orderId);
//            orderDetail.setNumber(item.getNumber());
//            orderDetail.setDishFlavor(item.getDishFlavor());
//            orderDetail.setDishId(item.getDishId());
//            orderDetail.setSetmealId(item.getSetmealId());
//            orderDetail.setName(item.getName());
//            orderDetail.setImage(item.getImage());
//            orderDetail.setAmount(item.getAmount());
//            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
//            return orderDetail;
//        }).collect(Collectors.toList());
//     orderDetailService.saveBatch(orderDetails);
//        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
//        return R.success(null);
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> page(int page,int pageSize){
        //Page<OrderDetail> orderDetailPage = new Page<>(page, pageSize);
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        ordersLambdaQueryWrapper.orderByDesc(Orders::getCheckoutTime);
        orderService.page(ordersPage,ordersLambdaQueryWrapper);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<OrdersDto> ordersDtoList = ordersPage.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);


        //List<Orders> orderslist = orderService.list(ordersLambdaQueryWrapper);
//        List<OrdersDto> ordersDtoList = orderslist.stream().map(orders -> {
//            OrdersDto ordersDto = new OrdersDto();
//            BeanUtils.copyProperties(orders, ordersDto);
//            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
//            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
//            ordersDto.setOrderDetails(orderDetailList);
//            return ordersDto;
//        }).collect(Collectors.toList());


//        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        orderDetailLambdaQueryWrapper.orderByDesc(OrderDetail::getDishId)



    }
}
